package com.kobe.algorithm.leetcode.case16;

import com.kobe.algorithm.leetcode.case15.Solution;

import java.util.Arrays;

/**
 * @author ：caopengfei
 * @date ：2021/2/24
 */
public class Soultion16 {

    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        Arrays.sort(nums);
        int moreNear = 0;
        int sumAll = 0;
        for (int first = 0; first < n; first++) {
            if(first >0 && nums[first] == nums[first-1]){
                continue;
            }
            int thrid = n-1;
            for (int second = first+1; second < n; second++) {
                if(second >first+1 && nums[second] == nums[second-1]){
                    continue;
                }

                while(second < thrid){
                    int sumAllTmp  = nums[first]+nums[second]+nums[thrid];
                    int moreNearTemp = target-sumAll;
                    if(moreNearTemp == 0){
                         return sumAll;
                    }
                    if(moreNearTemp < moreNear){
                        moreNear = moreNearTemp;
                        sumAll = sumAllTmp;
                    }else{
                        --thrid;
                    }
                }
            }
        }
        return sumAll;
    }


    public static void main(String[] args) {
        Soultion16 solution = new Soultion16();
        int [] nums = {-1,2,1,-4};
        System.out.println(solution.threeSumClosest(nums,1));

    }
}

